{% extends "base.html" %}

{% block title %}预约详情{% endblock %}

{% block extra_css %}
<style>
    .detail-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 2rem 0;
        border-radius: 0 0 1rem 1rem;
        margin-bottom: 2rem;
    }

    .reservation-card {
        background: white;
        border-radius: 1rem;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        margin-bottom: 2rem;
    }

    .reservation-header {
        background: linear-gradient(135deg, #f8f9fa, #e9ecef);
        padding: 1.5rem;
        border-bottom: 1px solid #e9ecef;
    }

    .status-badge {
        font-size: 1rem;
        padding: 0.5rem 1rem;
        border-radius: 0.5rem;
        font-weight: 600;
    }

    .status-badge.pending {
        background: linear-gradient(135deg, #ffc107, #fd7e14);
        color: white;
    }

    .status-badge.confirmed {
        background: linear-gradient(135deg, #28a745, #20c997);
        color: white;
    }

    .status-badge.completed {
        background: linear-gradient(135deg, #6c757d, #495057);
        color: white;
    }

    .status-badge.cancelled {
        background: linear-gradient(135deg, #dc3545, #c82333);
        color: white;
    }

    .status-badge.no_show {
        background: linear-gradient(135deg, #6f42c1, #563d7c);
        color: white;
    }

    .info-section {
        padding: 1.5rem;
    }

    .info-item {
        display: flex;
        align-items: center;
        padding: 0.75rem 0;
        border-bottom: 1px solid #f8f9fa;
    }

    .info-item:last-child {
        border-bottom: none;
    }

    .info-icon {
        width: 40px;
        height: 40px;
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
        border-radius: 0.5rem;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 1rem;
        flex-shrink: 0;
    }

    .info-content {
        flex: 1;
    }

    .info-label {
        font-size: 0.875rem;
        color: #6c757d;
        margin-bottom: 0.25rem;
    }

    .info-value {
        font-weight: 600;
        color: #2c3e50;
        font-size: 1rem;
    }

    .timeline {
        position: relative;
        padding-left: 2rem;
    }

    .timeline::before {
        content: '';
        position: absolute;
        left: 1rem;
        top: 0;
        bottom: 0;
        width: 2px;
        background: linear-gradient(to bottom, #667eea, #764ba2);
    }

    .timeline-item {
        position: relative;
        padding: 1rem 0;
        padding-left: 1.5rem;
    }

    .timeline-item::before {
        content: '';
        position: absolute;
        left: -0.5rem;
        top: 1.5rem;
        width: 12px;
        height: 12px;
        background: #667eea;
        border-radius: 50%;
        border: 3px solid white;
        box-shadow: 0 0 0 3px #667eea;
    }

    .timeline-item.current::before {
        background: #28a745;
        box-shadow: 0 0 0 3px #28a745;
    }

    .timeline-content {
        background: white;
        border: 1px solid #e9ecef;
        border-radius: 0.5rem;
        padding: 1rem;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .timeline-time {
        font-size: 0.875rem;
        color: #6c757d;
        margin-bottom: 0.5rem;
    }

    .timeline-title {
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 0.5rem;
    }

    .timeline-desc {
        font-size: 0.875rem;
        color: #6c757d;
    }

    .action-buttons {
        padding: 1.5rem;
        background: #f8f9fa;
        border-top: 1px solid #e9ecef;
    }

    .countdown-timer {
        background: linear-gradient(135deg, #ff6b6b, #ff8e53);
        color: white;
        padding: 1rem;
        border-radius: 0.5rem;
        text-align: center;
        margin-bottom: 1rem;
    }

    .countdown-time {
        font-size: 2rem;
        font-weight: bold;
        margin-bottom: 0.5rem;
    }

    .countdown-label {
        font-size: 0.875rem;
        opacity: 0.9;
    }

    .student-info {
        background: linear-gradient(135deg, #e3f2fd, #bbdefb);
        border-radius: 0.75rem;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
    }

    .student-avatar {
        width: 60px;
        height: 60px;
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
        font-weight: bold;
        margin-right: 1rem;
    }

    .student-details {
        flex: 1;
    }

    .student-name {
        font-size: 1.25rem;
        font-weight: bold;
        color: #2c3e50;
        margin-bottom: 0.25rem;
    }

    .student-meta {
        color: #6c757d;
        font-size: 0.875rem;
    }

    .price-info {
        background: linear-gradient(135deg, #fff3cd, #ffeaa7);
        border-radius: 0.75rem;
        padding: 1.5rem;
        margin-bottom: 1.5rem;
        text-align: center;
    }

    .price-amount {
        font-size: 2.5rem;
        font-weight: bold;
        color: #f39c12;
        margin-bottom: 0.5rem;
    }

    .price-label {
        color: #6c757d;
        font-size: 0.875rem;
    }

    .qr-code-section {
        text-align: center;
        padding: 1.5rem;
        background: #f8f9fa;
        border-radius: 0.75rem;
        margin-bottom: 1.5rem;
    }

    .qr-code {
        width: 150px;
        height: 150px;
        margin: 0 auto 1rem;
        border: 2px solid #e9ecef;
        border-radius: 0.5rem;
        background: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 0.875rem;
        color: #6c757d;
    }

    .notes-section {
        background: #fff3cd;
        border-left: 4px solid #ffc107;
        border-radius: 0 0.5rem 0.5rem 0;
        padding: 1rem;
        margin-bottom: 1.5rem;
    }

    .cancel-policy {
        background: #f8d7da;
        border-left: 4px solid #dc3545;
        border-radius: 0 0.5rem 0.5rem 0;
        padding: 1rem;
        margin-bottom: 1.5rem;
    }

    @media (max-width: 768px) {
        .detail-header {
            padding: 1rem 0;
        }

        .info-item {
            flex-direction: column;
            align-items: flex-start;
            text-align: left;
        }

        .info-icon {
            margin-bottom: 0.5rem;
            margin-right: 0;
        }

        .timeline {
            padding-left: 1rem;
        }

        .timeline-item {
            padding-left: 1rem;
        }

        .countdown-time {
            font-size: 1.5rem;
        }

        .price-amount {
            font-size: 2rem;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="detail-header">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h1 class="mb-0">
                    <i class="fas fa-calendar-check me-2"></i>预约详情
                </h1>
                <p class="mb-0 mt-2 opacity-75">预约编号：#{{ reservation.id }}</p>
            </div>
            <div class="col-md-4 text-end">
                <a href="{{ url_for('coach_reservations.confirmed') }}" class="btn btn-light">
                    <i class="fas fa-arrow-left me-1"></i>返回列表
                </a>
            </div>
        </div>
    </div>
</div>

<div class="container">
    <div class="row">
        <div class="col-lg-8">
            <!-- 预约基本信息 -->
            <div class="reservation-card">
                <div class="reservation-header">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h3 class="mb-1">预约信息</h3>
                            <p class="mb-0 text-muted">
                                创建时间：{{ reservation.created_at.strftime('%Y-%m-%d %H:%M') }}
                            </p>
                        </div>
                        <div class="col-md-4 text-end">
                            <span class="status-badge {{ reservation.status }}">
                                {{ reservation.status_text }}
                            </span>
                        </div>
                    </div>
                </div>

                <div class="info-section">
                    <div class="info-item">
                        <div class="info-icon">
                            <i class="fas fa-calendar-alt"></i>
                        </div>
                        <div class="info-content">
                            <div class="info-label">预约日期</div>
                            <div class="info-value">{{ reservation.reservation_date.strftime('%Y年%m月%d日 %A') }}</div>
                        </div>
                    </div>

                    <div class="info-item">
                        <div class="info-icon">
                            <i class="fas fa-clock"></i>
                        </div>
                        <div class="info-content">
                            <div class="info-label">上课时间</div>
                            <div class="info-value">
                                {{ reservation.start_time.strftime('%H:%M') }} - {{ reservation.end_time.strftime('%H:%M') }}
                                <span class="text-muted">({{ reservation.duration_minutes }}分钟)</span>
                            </div>
                        </div>
                    </div>

                    <div class="info-item">
                        <div class="info-icon">
                            <i class="fas fa-table-tennis"></i>
                        </div>
                        <div class="info-content">
                            <div class="info-label">球台</div>
                            <div class="info-value">{{ reservation.table.name }} ({{ reservation.campus.name }})</div>
                        </div>
                    </div>

                    <div class="info-item">
                        <div class="info-icon">
                            <i class="fas fa-map-marker-alt"></i>
                        </div>
                        <div class="info-content">
                            <div class="info-label">上课地点</div>
                            <div class="info-value">{{ reservation.table.campus.address }}</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 学员信息 -->
            <div class="reservation-card">
                <div class="reservation-header">
                    <h3 class="mb-0">学员信息</h3>
                </div>

                <div class="info-section">
                    <div class="student-info">
                        <div class="d-flex align-items-center">
                            <div class="student-avatar">
                                {{ reservation.student.real_name[0] }}
                            </div>
                            <div class="student-details">
                                <div class="student-name">{{ reservation.student.real_name }}</div>
                                <div class="student-meta">
                                    <i class="fas fa-phone me-1"></i>{{ reservation.student.phone }}
                                    {% if reservation.student.email %}
                                    | <i class="fas fa-envelope me-1"></i>{{ reservation.student.email }}
                                    {% endif %}
                                </div>
                            </div>
                            <div>
                                <a href="tel:{{ reservation.student.phone }}" class="btn btn-outline-primary btn-sm">
                                    <i class="fas fa-phone me-1"></i>拨打
                                </a>
                            </div>
                        </div>
                    </div>

                    {% if reservation.student.level %}
                    <div class="info-item">
                        <div class="info-icon">
                            <i class="fas fa-star"></i>
                        </div>
                        <div class="info-content">
                            <div class="info-label">技术水平</div>
                            <div class="info-value">{{ reservation.student.level_text }}</div>
                        </div>
                    </div>
                    {% endif %}

                    {% if reservation.student.notes %}
                    <div class="info-item">
                        <div class="info-icon">
                            <i class="fas fa-sticky-note"></i>
                        </div>
                        <div class="info-content">
                            <div class="info-label">学员备注</div>
                            <div class="info-value">{{ reservation.student.notes }}</div>
                        </div>
                    </div>
                    {% endif %}
                </div>
            </div>

            <!-- 预约备注 -->
            {% if reservation.notes %}
            <div class="notes-section">
                <h6><i class="fas fa-sticky-note me-2"></i>预约备注</h6>
                <p class="mb-0">{{ reservation.notes }}</p>
            </div>
            {% endif %}

            <!-- 取消政策 -->
            {% if reservation.status in ['pending', 'confirmed'] %}
            <div class="cancel-policy">
                <h6><i class="fas fa-exclamation-triangle me-2"></i>取消政策</h6>
                <ul class="mb-0">
                    <li>课程开始前24小时可免费取消</li>
                    <li>课程开始前2-24小时取消收取50%费用</li>
                    <li>课程开始前2小时内取消或未到场收取全额费用</li>
                    <li>每月最多可取消3次，超出后取消将收取额外费用</li>
                </ul>
            </div>
            {% endif %}
        </div>

        <div class="col-lg-4">
            <!-- 倒计时（如果是即将开始的课程） -->
            {% if reservation.status == 'confirmed' and reservation.is_upcoming %}
            <div class="countdown-timer" id="countdownTimer">
                <div class="countdown-time" id="countdownTime">
                    {{ reservation.time_until_start }}
                </div>
                <div class="countdown-label">距离课程开始</div>
            </div>
            {% endif %}

            <!-- 课程费用 -->
            {% if reservation.price %}
            <div class="price-info">
                <div class="price-amount">¥{{ reservation.price }}</div>
                <div class="price-label">课程费用</div>
            </div>
            {% endif %}

            <!-- 签到二维码（仅确认状态显示） -->
            {% if reservation.status == 'confirmed' and reservation.is_today %}
            <div class="qr-code-section">
                <h6><i class="fas fa-qrcode me-2"></i>签到二维码</h6>
                <div class="qr-code">
                    <div id="qrcode" style="width: 120px; height: 120px; background: #f8f9fa; border: 2px dashed #dee2e6; display: flex; align-items: center; justify-content: center; font-size: 3rem; color: #6c757d;">
                        <i class="fas fa-qrcode"></i>
                    </div>
                </div>
                <p class="text-muted mb-0">学员扫码即可签到上课</p>
                <small class="text-muted">预约ID: {{ reservation.id }}</small>
            </div>
            {% endif %}

            <!-- 操作按钮 -->
            <div class="action-buttons">
                {% if reservation.status == 'pending' %}
                <div class="d-grid gap-2">
                    <button type="button" class="btn btn-success" onclick="confirmReservation()">
                        <i class="fas fa-check me-2"></i>确认预约
                    </button>
                    <button type="button" class="btn btn-outline-danger" onclick="rejectReservation()">
                        <i class="fas fa-times me-2"></i>拒绝预约
                    </button>
                </div>
                {% elif reservation.status == 'confirmed' %}
                <div class="d-grid gap-2">
                    {% if reservation.is_today or reservation.is_past %}
                    <button type="button" class="btn btn-success" onclick="completeReservation()">
                        <i class="fas fa-check-circle me-2"></i>标记完成
                    </button>
                    <button type="button" class="btn btn-outline-warning" onclick="markNoShow()">
                        <i class="fas fa-user-times me-2"></i>标记未到
                    </button>
                    {% endif %}
                    {% if reservation.can_cancel %}
                    <button type="button" class="btn btn-outline-danger" onclick="cancelReservation()">
                        <i class="fas fa-ban me-2"></i>取消预约
                    </button>
                    {% endif %}
                </div>
                {% endif %}

                <hr>

                <div class="d-grid gap-2">
                    <a href="{{ url_for('coach_reservations.schedule') }}" class="btn btn-outline-primary">
                        <i class="fas fa-calendar me-2"></i>查看课程表
                    </a>
                    <button type="button" class="btn btn-outline-info" onclick="printReservation()">
                        <i class="fas fa-print me-2"></i>打印详情
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 操作历史 -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="reservation-card">
                <div class="reservation-header">
                    <h3 class="mb-0">操作历史</h3>
                </div>

                <div class="info-section">
                    <div class="timeline">
                        <div class="timeline-item current">
                            <div class="timeline-content">
                                <div class="timeline-time">{{ reservation.created_at.strftime('%Y-%m-%d %H:%M') }}</div>
                                <div class="timeline-title">学员提交预约申请</div>
                                <div class="timeline-desc">{{ reservation.student.real_name }} 申请预约课程</div>
                            </div>
                        </div>



                        {% if reservation.cancelled_at %}
                        <div class="timeline-item current">
                            <div class="timeline-content">
                                <div class="timeline-time">{{ reservation.cancelled_at.strftime('%Y-%m-%d %H:%M') }}</div>
                                <div class="timeline-title">预约已取消</div>
                                <div class="timeline-desc">
                                    {% if reservation.cancel_reason %}
                                        取消原因：{{ reservation.cancel_reason }}
                                    {% else %}
                                        预约已取消
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 拒绝预约模态框 -->
<div class="modal fade" id="rejectModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">拒绝预约</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">拒绝原因（选填）</label>
                    <textarea class="form-control" id="rejectReason" rows="3" placeholder="请输入拒绝原因..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmReject()">确认拒绝</button>
            </div>
        </div>
    </div>
</div>

<!-- 取消预约模态框 -->
<div class="modal fade" id="cancelModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">取消预约</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>注意：</strong>根据取消政策，此次取消可能会产生费用。
                </div>
                <div class="mb-3">
                    <label class="form-label">取消原因（必填）</label>
                    <textarea class="form-control" id="cancelReason" rows="3" placeholder="请输入取消原因..." required></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">返回</button>
                <button type="button" class="btn btn-danger" onclick="confirmCancel()">确认取消</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 倒计时更新
    {% if reservation.status == 'confirmed' and reservation.is_upcoming %}
    updateCountdown();
    setInterval(updateCountdown, 1000);
    {% endif %}
});

// 更新倒计时
function updateCountdown() {
    const now = new Date();
    const startTime = new Date('{{ reservation.reservation_date.strftime("%Y-%m-%d") }} {{ reservation.start_time.strftime("%H:%M") }}');
    const diff = startTime - now;

    if (diff <= 0) {
        $('#countdownTimer').html(`
            <div class="countdown-time">课程进行中</div>
            <div class="countdown-label">请确保学员已到场</div>
        `);
        return;
    }

    const hours = Math.floor(diff / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((diff % (1000 * 60)) / 1000);

    let timeText = '';
    if (hours > 0) {
        timeText = `${hours}小时${minutes}分钟`;
    } else if (minutes > 0) {
        timeText = `${minutes}分${seconds}秒`;
    } else {
        timeText = `${seconds}秒`;
    }

    $('#countdownTime').text(timeText);
}

// 确认预约
function confirmReservation() {
    if (!confirm('确定要确认这个预约吗？')) return;

    $.post('{{ url_for("coach_reservations.api_confirm_reservation", reservation_id=reservation.id) }}', function(response) {
        if (response.success) {
            showAlert('success', '预约已确认');
            setTimeout(() => location.reload(), 1500);
        } else {
            showAlert('error', response.message || '确认预约失败');
        }
    }).fail(function() {
        showAlert('error', '网络错误，请重试');
    });
}

// 拒绝预约
function rejectReservation() {
    $('#rejectModal').modal('show');
}

function confirmReject() {
    const reason = $('#rejectReason').val();

    $.post('{{ url_for("coach_reservations.api_reject_reservation", reservation_id=reservation.id) }}', {
        reason: reason
    }, function(response) {
        if (response.success) {
            showAlert('success', '预约已拒绝');
            $('#rejectModal').modal('hide');
            setTimeout(() => location.reload(), 1500);
        } else {
            showAlert('error', response.message || '拒绝预约失败');
        }
    }).fail(function() {
        showAlert('error', '网络错误，请重试');
    });
}

// 完成预约
function completeReservation() {
    if (!confirm('确定要标记这个预约为已完成吗？')) return;

    $.post('{{ url_for("coach_reservations.api_complete_reservation", reservation_id=reservation.id) }}', function(response) {
        if (response.success) {
            showAlert('success', '预约已完成');
            setTimeout(() => location.reload(), 1500);
        } else {
            showAlert('error', response.message || '完成预约失败');
        }
    }).fail(function() {
        showAlert('error', '网络错误，请重试');
    });
}

// 标记未到
function markNoShow() {
    if (!confirm('确定要标记学员未到场吗？此操作不可撤销。')) return;

    $.post('{{ url_for("coach_reservations.api_mark_no_show", reservation_id=reservation.id) }}', function(response) {
        if (response.success) {
            showAlert('success', '已标记为未到场');
            setTimeout(() => location.reload(), 1500);
        } else {
            showAlert('error', response.message || '标记失败');
        }
    }).fail(function() {
        showAlert('error', '网络错误，请重试');
    });
}

// 取消预约
function cancelReservation() {
    $('#cancelModal').modal('show');
}

function confirmCancel() {
    const reason = $('#cancelReason').val().trim();
    if (!reason) {
        showAlert('error', '请输入取消原因');
        return;
    }

    $.post('{{ url_for("coach_reservations.api_cancel_reservation", reservation_id=reservation.id) }}', {
        reason: reason
    }, function(response) {
        if (response.success) {
            showAlert('success', '预约已取消');
            $('#cancelModal').modal('hide');
            setTimeout(() => location.reload(), 1500);
        } else {
            showAlert('error', response.message || '取消预约失败');
        }
    }).fail(function() {
        showAlert('error', '网络错误，请重试');
    });
}

// 打印预约详情
function printReservation() {
    window.print();
}

// 显示提示信息
function showAlert(type, message) {
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    const icon = type === 'success' ? 'check-circle' : 'exclamation-triangle';

    const alert = $(`
        <div class="alert ${alertClass} alert-dismissible fade show position-fixed"
             style="top: 20px; right: 20px; z-index: 9999;">
            <i class="fas fa-${icon} me-2"></i>${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `);

    $('body').append(alert);

    setTimeout(function() {
        alert.alert('close');
    }, 3000);
}
</script>
{% endblock %}